
<!DOCTYPE html>
<html lang="">


<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no">
  <meta name="theme-color" content="#202020"/>
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  <script src="/js/busuanzi.pure.mini.js" async></script>
  
  
    <meta name="keywords" content="Emberjs,Ember-Teach,Ember-Template," />
  

  
    <meta name="description" content="一个专注一coding的网站。提供丰富编程知识，包括Spring、Java、EmberJS、SpringBoot等等技术。" />
  
  
  <link rel="icon" type="image/x-icon" href="/image/favicon.ico">
  <title>handlebars条件表达式 [ Keep Coding ]</title>
  
    <!-- stylesheets list from config.yml -->
    
      <link rel="stylesheet" href="/css/pure-min.css">
    
      <link rel="stylesheet" href="/css/xoxo.css">
    
  
<meta name="generator" content="Hexo 5.0.2"><link rel="alternate" href="/atom.xml" title="Keep Coding" type="application/atom+xml">
</head>

<body>
  <div class="nav-container">
    <nav class="home-menu pure-menu pure-menu-horizontal">
  <a class="pure-menu-heading" href="/">
    <img class="avatar" src="/image/favicon.ico">
    <span class="title">Keep Coding</span>
  </a>

  <ul class="pure-menu-list clearfix">
      
          
            <li class="pure-menu-item"><a href="/" class="pure-menu-link">首页</a></li>
          
      
          
            <li class="pure-menu-item"><a href="/archives" class="pure-menu-link">归档</a></li>
          
      
          
            <li class="pure-menu-item"><a href="/tags" class="pure-menu-link">标签</a></li>
          
      
          
            <li class="pure-menu-item"><a href="/search" class="pure-menu-link">搜索</a></li>
          
      
          
            <li class="pure-menu-item"><a href="/about" class="pure-menu-link">关于</a></li>
          
      
          
            <li class="pure-menu-item"><a href="/atom.xml" class="pure-menu-link">订阅</a></li>
          
      
  </ul>
   
</nav>
  </div>

  <div class="container" id="content-outer">
    <div class="inner" id="content-inner">
      <div class="post-container">
  <article class="post" id="post">
    <header class="post-header text-center">
      <h1 class="title">
        handlebars条件表达式
      </h1>
      <span>
        
        <time class="time" datetime="2020-01-18T14:50:37.000Z">
        2020-01-18
      </time>
        
      </span>
      <span class="slash">/</span>
      <span class="post-meta">
      <span class="post-tags">
        <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/Ember-Teach/" rel="tag">Ember-Teach</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/Ember-Template/" rel="tag">Ember-Template</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/Emberjs/" rel="tag">Emberjs</a></li></ul>
      </span>
    </span>
      <span class="slash">/</span>
      <span class="read">
      <span id="busuanzi_value_page_pv"></span> 点击
    </span>
      <span class="slash">/</span>
      <span class="read">阅读耗时 2 分钟</span>
    </header>

    <div class="post-content">
      <p><code>handlebars</code>模板提供了与一般语言类似的条件表达式，比如<code>if</code>、<code>if⋯⋯else⋯⋯</code>。<br>在介绍这些条件表达式之前，我们先做好演示的准备工作。首先我会使用<code>Ember CLI</code>命令创建<code>route</code>、<code>template</code>，然后在创建的<code>template</code>上编写<code>handlebars</code>模板代码。<br>先创建<code>route</code>：<br><br><code>ember generate route handlbars-conditions-exp-route</code><br><br>或者：<br><br><code>ember generate route handlbarsConditionsExpRoute</code><br><br>这两个命令创建的文件名都是一样的。最后<code>Ember CLI</code>会为我们自动创建2个主要的文件：<code>app/templates/handlbars-conditions-exp-route.hbs</code>  和 <code>app/routes/handlbars-conditions-exp-route.js</code></p>
<p><strong>注意：如果你使用的是驼峰式的名称<code>Ember CLI</code>会根据<code>Ember</code>的命名规范自动创建以中划线<code>-</code>分隔的名称。为什么我是先使用命令创建<code>route</code>而不是<code>template</code>呢？？因为你创建<code>route</code>的同时<code>Ember CLI</code>会自动给你创建一个对应的模板文件，如果你是先创建<code>template</code>的话，你还需要手动再执行创建<code>route</code>的命令，即你要执行2条命令(<code>ember generate template handlbars-conditions-exp-route</code>和<code>ember generate route handlbars-conditions-exp-route</code>)。</strong></p>
<p>得到演示所需要的文件后回到正题，开始介绍<code>handlebars</code>的条件判断表达式。<br>为了演示先在<code>route</code>文件添加模拟条件代码：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//  app/routes/handlebars-condition-exp-route.js</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> Ember <span class="keyword">from</span> <span class="string">&#x27;ember&#x27;</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> Ember.Route.extend(&#123;</span><br><span class="line"></span><br><span class="line">    model: <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> &#123;<span class="attr">name</span>: <span class="string">&#x27;i2cao.xyz&#x27;</span>, <span class="attr">age</span>: <span class="number">25</span>, <span class="attr">isAtWork</span>: <span class="literal">false</span>, <span class="attr">isReading</span>: <span class="literal">false</span> &#125;;</span><br><span class="line">        <span class="comment">// return &#123; enable: true &#125;;</span></span><br><span class="line">    &#125;       </span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>对于<code>handlebars-condition-exp-route.js</code>这个文件的内容会在后面路由这一章详细介绍，你可以暂且当做是返回了一个对象到模板上。与<code>EL</code>表达式非常类似，你可以用<code>.</code>获取对象里的属性值（如：<code>person.name</code>）。</p>
<h3 id="1，if表达式"><a href="#1，if表达式" class="headerlink" title="1，if表达式"></a>1，<code>if</code>表达式</h3><figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!-- app/templates/handlbars-conditions-exp-route.hbs --&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="comment">&lt;!-- if判断标签，当model的值不为 false, undefined, null or [] 的时候显示标签内的内容 --&gt;</span></span><br><span class="line">&#123;&#123;#if model&#125;&#125;</span><br><span class="line">Welcome back, <span class="tag">&lt;<span class="name">b</span>&gt;</span>&#123;&#123;model.name&#125;&#125;<span class="tag">&lt;/<span class="name">b</span>&gt;</span> !</span><br><span class="line">&#123;&#123;/if&#125;&#125;</span><br></pre></td></tr></table></figure>

<p><img src="/content/images/2016/03/17.png" alt="run result"></p>
<p>每个条件表达式都要以<code>#</code>开头并且要有对应的关闭标签，但是对于<code>if</code>标签来说不是必须要关闭标签的，这里简单举个例子：</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!-- 没有关闭关闭标签的if用法 --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">&quot;&#123;&#123;if flag &#x27;show&#x27; &#x27;hide&#x27;&#125;&#125;&quot;</span>&gt;</span></span><br><span class="line">测试内容</span><br><span class="line"><span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>这个<code>if</code>标签相当于一个<code>三元运算符</code>,只是省略了<code>?</code>和<code>:</code>,他会根据属性<code>flag</code>的值判断是显示那个CSS类，如果<code>flag</code>的值不是<code>false</code>，不是<code>[]</code>空数组，也不是<code>null</code>，也不是<code>undefined</code>则<code>div</code>会加上CSS类<code>show</code>，模板编译之后的标签为<code>&lt;div class=&quot;show&quot;&gt;</code>，否则会加CSS类<code>hide</code>模板编译之后的标签为<code>&lt;div class=&quot;hide&quot;&gt;</code>。这样解释应该很容易理解了，其实说白了就一个<code>if</code>判断。没别的难点。。。</p>
<p>运行的时候需要注意两个地方，一个是浏览器执行的<code>URL</code>。如果你也是使用驼峰式的命名方式（创建命名：<code>ember generate route handlbarsConditionsExpRoute</code>），那你的<code>URL</code>跟我的是一样的，反正你只要记得执行的<code>URL</code>跟你创建的<code>route</code>的名称是一致的。当然这个名字是可以修改的。在<code>app/router.js</code>里面修改，在<code>Router.map</code>里的代码也是<code>Ember CLI</code>自动创建的。我们可以看到有一个<code>this.route(&#39;handlebarsConditionsExpRoute&#39;);</code>这个就是你的路由的名称。</p>
<p><strong>建议：创建之后的路由名字最好不要修改，<code>ember</code>会根据默认的命名规范查找<code>route</code>对应的<code>template</code>，如果你修改了<code>router.js</code>里的名字你需要同时修改<code>app/routes</code> 和 <code>app/templates</code> 里相对应的文件名。否则<code>URL</code>上的路由无法找到对应的<code>template</code>显示你的内容，在<code>router.js</code>里配置的名字必须与<code>app/routes</code>目录下的路由文件名字对应，模板的名字不一定要与路由配置名称对应，应该可以在<code>route</code>类中指定渲染的模板是那个，这个后面的内容会讲到（不是重点内容，了解即可）。<br>说明：可能你看到的我截图给你的有点差别，是因为我修改了主模板(<code>app/index.html</code>)你可以在这个文件里添加自己喜欢的样式，你一在<code>app/index.html</code>引入你的样式，或者在<code>ember-cli-build.js</code>引入第三方样式都可以，自定义的样式放在<code>public/assets/</code>下，如果没有目录可以自行手动创建，在此就不再赘述，这个不是本文的重点。</strong></p>
<h3 id="2，if⋯⋯else⋯⋯表达式"><a href="#2，if⋯⋯else⋯⋯表达式" class="headerlink" title="2，if⋯⋯else⋯⋯表达式"></a>2，<code>if⋯⋯else⋯⋯</code>表达式</h3><figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!-- app/templates/handlebars-conditions-exp-route.hbs --&gt;</span></span><br><span class="line"><span class="comment">&lt;!-- if⋯⋯else⋯⋯判断 --&gt;</span></span><br><span class="line">&#123;&#123;#if model.isAtWork&#125;&#125;</span><br><span class="line">Ship that code..<span class="tag">&lt;<span class="name">br</span>&gt;</span></span><br><span class="line">&#123;&#123;else if model.isReading&#125;&#125;</span><br><span class="line">You can finish War and Peace eventually..<span class="tag">&lt;<span class="name">br</span>&gt;</span></span><br><span class="line">&#123;&#123;else&#125;&#125;</span><br><span class="line">This is else block...</span><br><span class="line">&#123;&#123;/if&#125;&#125;</span><br></pre></td></tr></table></figure>
<p>结果是输出：This is else block…<br>因为<code>isAtWork</code>和<code>isReading</code>都是<code>false</code>。读者可以自己修改<code>app/routes/handlebars-condition-exp-route.js</code>里面对应的值然后查看输出结果。</p>
<h3 id="3，unless表达式"><a href="#3，unless表达式" class="headerlink" title="3，unless表达式"></a>3，<code>unless</code>表达式</h3><p><code>unless</code>表达式类似于非操作，当<code>model.isReading</code>值为<code>false</code>的时候会输出表达式里面的内容。</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!-- app/templates/handlebars-conditions-exp-route.hbs --&gt;</span></span><br><span class="line"><span class="comment">&lt;!-- 非判断 --&gt;</span></span><br><span class="line">&#123;&#123;#unless model.isReading&#125;&#125;</span><br><span class="line">unless.....</span><br><span class="line">&#123;&#123;/unless&#125;&#125;</span><br></pre></td></tr></table></figure>

<p>如果<code>isReading</code>值为<code>false</code>会输出<code>unless⋯</code>否则不进入表达式内。</p>
<h3 id="4，在HTML标签内使用表达式"><a href="#4，在HTML标签内使用表达式" class="headerlink" title="4，在HTML标签内使用表达式"></a>4，在HTML标签内使用表达式</h3><p><code>handlebars</code>表达式可以直接在嵌入到<code>HTML</code>标签内。</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!-- app/templates/handlebars-conditions-exp-route.hbs --&gt;</span></span><br><span class="line"><span class="comment">&lt;!-- 可以把表达式直接嵌入在某个标签中，当enable的值为true则结果是增加了一个类(css的类)enable，否则增加&#x27;disable&#x27; --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">span</span> <span class="attr">class</span>=<span class="string">&#123;&#123;if</span> <span class="attr">enable</span> &#x27;<span class="attr">enable</span>&#x27; &#x27;<span class="attr">disable</span>&#x27;&#125;&#125;&gt;</span>enable or disable<span class="tag">&lt;/<span class="name">span</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>说白了其实就是一个三目运算。不难理解。不过这个例子与第一点讲没有关闭标签的<code>if</code>例子一致，就当是复习吧=^=。</p>
<p>上述就是<code>handlebars</code>中最常用的几个条件表达式，自己作为小例子演示一遍肯定懂了，对于有点惊讶的开发者甚至看一遍即可。非常的简单，可能后面还会有其他的条件判断的表达式，后续会补上。<br><br><br>博文完整代码放在<a target="_blank" rel="noopener" href="https://github.com/ubuntuvim/my_emberjs_code">Github</a>（博文经过多次修改，博文上的代码与github代码可能又出入，不过影响不大！），如果你觉得博文对你有点用，请在github项目上给我点个<code>star</code>吧。您的肯定对我来说是最大的动力！！</p>

    </div>

      
    <div class="post-nav">
      <div class="post-nav-item post-nav-next">
        
          <span>〈 </span>
          <a href="/2020/01/18/ember-teach/templetes/handlebars%E9%81%8D%E5%8E%86%E6%A0%87%E7%AD%BE/" rel="next" title="handlebars遍历标签">
          handlebars遍历标签
          </a>
        
      </div>
  
      <div class="post-nav-item post-nav-prev">
          
          <a href="/2020/01/18/ember-teach/templetes/handlebars%E6%98%BE%E7%A4%BA%E5%AF%B9%E8%B1%A1%E7%9A%84%E9%94%AE/" rel="prev" title="handlebars显示对象的键">
            handlebars显示对象的键
          </a>
          <span>〉</span>
        
      </div>
    </div>
  
  </article>
  <div class="toc-container">
    
  <div id="toc" class="toc-article">
    <strong class="toc-title">目录</strong>
    <ol class="toc"><li class="toc-item toc-level-3"><a class="toc-link" href="#1%EF%BC%8Cif%E8%A1%A8%E8%BE%BE%E5%BC%8F"><span class="toc-text">1，if表达式</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2%EF%BC%8Cif%E2%8B%AF%E2%8B%AFelse%E2%8B%AF%E2%8B%AF%E8%A1%A8%E8%BE%BE%E5%BC%8F"><span class="toc-text">2，if⋯⋯else⋯⋯表达式</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3%EF%BC%8Cunless%E8%A1%A8%E8%BE%BE%E5%BC%8F"><span class="toc-text">3，unless表达式</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4%EF%BC%8C%E5%9C%A8HTML%E6%A0%87%E7%AD%BE%E5%86%85%E4%BD%BF%E7%94%A8%E8%A1%A8%E8%BE%BE%E5%BC%8F"><span class="toc-text">4，在HTML标签内使用表达式</span></a></li></ol>
  </div>


  </div>
</div>


<div class="copyright">
    <span>本作品采用</span>
    <a target="_blank" rel="noopener" href="https://creativecommons.org/licenses/by/4.0/">知识共享署名 4.0 国际许可协议</a>
    <span>进行许可。 转载时请注明原文链接。</span>
</div>
<div class="share">

</div>
<div class="post-container">
    <article class="post">
      <div id="container"></div>
    </article>
</div>

<link rel="stylesheet" href="https://imsun.github.io/gitment/style/default.css">
<script src="https://imsun.github.io/gitment/dist/gitment.browser.js"></script>
<script>
var gitment = new Gitment({
  id: 'handlebars条件表达式', // 可选。默认为 location.href
  owner: 'ubuntuvim',
  repo: 'ubuntuvim.github.io',
  oauth: {
    client_id: '48b3df0bf4ba1743e0a3',
    client_secret: 'c6c2cec09acb5eecc9d325d56cef187264aa1e16',
  },
})
gitment.render('container')
</script>



    </div>

    

  </div>
  <footer class="footer text-center">
    <div id="bottom-inner">
        <a class="bottom-item" href="http://xcoding.tech/">首页</a> |
        <a class="bottom-item" href="http://xcoding.tech/" target="_blank">主站</a> |
        <a class="bottom-item" href="https://github.com/ubuntuvim" target="_blank">GitHub</a> |
        <a class="bottom-item" href="https://hexo.io" target="_blank">Powered by hexo</a> |
        <a class="bottom-item" href="https://github.com/KevinOfNeu/hexo-theme-xoxo" target="_blank">Theme xoxo</a>
    </div>
</footer>


  <script src='https://unpkg.com/mermaid@7.1.2/dist/mermaid.min.js'></script>
  <script>
    if (window.mermaid) {
      mermaid.initialize({theme: 'forest'});
    }
  </script>


  
  <!-- scripts list from theme config.yml -->
  
    <script src="/js/zepto.min.js"></script>
  


<script>
  (function(window, document, undefined) {

    var timer = null;

    function returnTop() {
      cancelAnimationFrame(timer);
      timer = requestAnimationFrame(function fn() {
        var oTop = document.body.scrollTop || document.documentElement.scrollTop;
        if (oTop > 0) {
          document.body.scrollTop = document.documentElement.scrollTop = oTop - 50;
          timer = requestAnimationFrame(fn);
        } else {
          cancelAnimationFrame(timer);
        }
      });
    }

    var hearts = [];
    window.requestAnimationFrame = (function() {
      return window.requestAnimationFrame ||
        window.webkitRequestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        window.oRequestAnimationFrame ||
        window.msRequestAnimationFrame ||
        function(callback) {
          setTimeout(callback, 1000 / 60);
        }
    })();
    init();

    function init() {
      css(".heart{z-index:9999;width: 10px;height: 10px;position: fixed;background: #f00;transform: rotate(45deg);-webkit-transform: rotate(45deg);-moz-transform: rotate(45deg);}.heart:after,.heart:before{content: '';width: inherit;height: inherit;background: inherit;border-radius: 50%;-webkit-border-radius: 50%;-moz-border-radius: 50%;position: absolute;}.heart:after{top: -5px;}.heart:before{left: -5px;}");
      attachEvent();
      gameloop();
      addMenuEvent();
    }

    function gameloop() {
      for (var i = 0; i < hearts.length; i++) {
        if (hearts[i].alpha <= 0) {
          document.body.removeChild(hearts[i].el);
          hearts.splice(i, 1);
          continue;
        }
        hearts[i].y--;
        hearts[i].scale += 0.004;
        hearts[i].alpha -= 0.013;
        hearts[i].el.style.cssText = "left:" + hearts[i].x + "px;top:" + hearts[i].y + "px;opacity:" + hearts[i].alpha + ";transform:scale(" + hearts[i].scale + "," + hearts[i].scale + ") rotate(45deg);background:" + hearts[i].color;
      }
      requestAnimationFrame(gameloop);
    }

    /**
     * 给logo设置点击事件
     * 
     * - 回到顶部
     * - 出现爱心
     */
    function attachEvent() {
      var old = typeof window.onclick === "function" && window.onclick;
      var logo = document.getElementById("logo");
      if (logo) {
        logo.onclick = function(event) {
          returnTop();
          old && old();
          createHeart(event);
        }
      }
      
    }

    function createHeart(event) {
      var d = document.createElement("div");
      d.className = "heart";
      hearts.push({
        el: d,
        x: event.clientX - 5,
        y: event.clientY - 5,
        scale: 1,
        alpha: 1,
        color: randomColor()
      });
      document.body.appendChild(d);
    }

    function css(css) {
      var style = document.createElement("style");
      style.type = "text/css";
      try {
        style.appendChild(document.createTextNode(css));
      } catch (ex) {
        style.styleSheet.cssText = css;
      }
      document.getElementsByTagName('head')[0].appendChild(style);
    }

    function randomColor() {
      // return "rgb(" + (~~(Math.random() * 255)) + "," + (~~(Math.random() * 255)) + "," + (~~(Math.random() * 255)) + ")";
      return "#F44336";
    }

    function addMenuEvent() {
      var menu = document.getElementById('menu-main-post');
      if (menu) {
        var toc = document.getElementById('toc');
        if (toc) {
          menu.onclick = function() {
            if (toc) {
              if (toc.style.display == 'block') {
                toc.style.display = 'none';
              } else {
                toc.style.display = 'block';
              }
            }
          };
        } else {
          menu.style.display = 'none';
        }
      }
    }

  })(window, document);
</script>

  



</body>
</html>
